package com.example.usermanage.controller;

import com.example.usermanage.model.Userinfo;
import com.example.usermanage.service.UserService;
import com.example.usermanage.tools.GetSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @GetMapping("/login")
    public Userinfo login(String username, String password, HttpServletRequest request){
        Userinfo userinfo = userService.login(username,password);
        if (userinfo != null){
            HttpSession session = request.getSession(true);
            session.setAttribute("userinfo",userinfo);
        }
        return userinfo;
    }

    @RequestMapping("/listAll")
    public List<Userinfo> listAll(HttpServletRequest request){
        if (GetSession.getSession(request) == 1){
            return userService.listAllPlus();
        }
        return userService.listAll();
    }
    @RequestMapping("/addList")
    public int addList(HttpServletRequest request){
        //拦截器已经判断过登录状态,这里可以不用判断
        return GetSession.getSession(request);
    }
    @RequestMapping("/insert")
    public int insert(Userinfo userinfo,HttpServletRequest request){
        //如果要添加的是管理员.判断当前是不是管理员在添加
        if (userinfo.getIsadmin() == 1){
            if(GetSession.getSession(request) == 1){
                return userService.insert(userinfo);
            }else {
                return -1;
            }
        }
        return userService.insert(userinfo);
    }
    @RequestMapping("/selectUpdate")
    public Userinfo selectUpdate(Integer id,HttpServletRequest request){
//        int tmp = GetSession.getSession(request);
        //判断是不是本人或管理员
        if (id == GetSession.getId(request)  || GetSession.getSession(request) == 1){
            return userService.selectUpdate(id);
        }
        Userinfo userinfo = new Userinfo();
        userinfo.setState(-1);
        return userinfo;

    }
    @Transactional
    @RequestMapping("/update")
    public int update(Userinfo userinfo,HttpServletRequest request){
        //如果要修改的是管理员.判断当前是不是管理员在添加
        if (userinfo.getIsadmin() == 1){
            if(GetSession.getSession(request) == 1){
                return userService.update(userinfo);
            }else {
                return -1;
            }
        }
        return userService.update(userinfo);

    }
    @GetMapping("/delete")
    public int delete(Integer id,HttpServletRequest request){
        if (id == GetSession.getId(request)  || GetSession.getSession(request) == 1){
            return userService.delete(id);
        }
        return -1;
    }
}
